package com.ynny.chapter14train.controller;


import com.ynny.chapter14train.pojo.Users;
import com.ynny.chapter14train.pojo.R;
import com.ynny.chapter14train.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;

    @GetMapping("/selectall")
    public R selectAll(@RequestBody Users users)
    {
        List<Users> usersList = usersService.selectAll(users);
         return R.ok(usersList);
    }

    @PostMapping("/add")
    public R add(@RequestBody Users users)
    {
        List<Users> i = usersService.insert(users);
        if(false)
        {
            return R.ok(i);
        }
        return R.fail(500,"添加失败");
    }


    @PostMapping("/register")
    public R register(@RequestBody Users users){
        //数据校验  -----》写在controller层
        if (users.getUsername().equals("") || users.getPassword().equals("")
                ||users.getIdentity().equals("")){

            return R.fail(221,"用户名密码或身份不能为空");
        }
        //注册功能

        int res = usersService.register( users);

        if (res == 205){
            return R.fail(205,"用户名已经存在");

        }
        users.setPassword(null);
        return R.ok(users);


    }
    @PostMapping("/login")
    public R login(@RequestBody Users users) {
        //用户账号密码身份都不可以为空
        if (users.getUsername().equals("") || users.getPassword().equals("")
        ) {

            return R.fail(221, "用户名密码或身份不能为空");
        }
        //账号密码不匹配不可以登录请输入准确密码
        if (usersService.login(users.getUsername(), users.getPassword()) == false) {
            return R.fail(222, "用户名或密码错误");

        }

        return R.ok(users);

    }


}
